package com.net.client;


import com.alibaba.fastjson.JSON;
import com.net.server.ConnectManager;
import com.pojo.ClientRunTimeInfo;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

@Component
public class NettyClient {

    public static String host = "127.0.0.1";
    public static int port = 7878;

    private Channel channel = null;

    @Autowired
    private ConnectManager connectManager;

    @Autowired
    private  NettyClientInitializer nettyClientInitializer;

    @PostConstruct
    public void init() throws InterruptedException, IOException {
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap b = new Bootstrap();
            b.group(group)
                    .channel(NioSocketChannel.class)
                    .handler(nettyClientInitializer);

            // 连接服务端
            channel = b.connect(host, port).sync().channel();

            new Thread(new Runnable() {
                @Override
                public void run() {
//                    loop();
                }
            }).start();
//            // 控制台输入
//            BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
//            for (;;) {
//                String line = in.readLine();
//                if (line == null) {
//                    continue;
//                }
//                /*
//                 * 向服务端发送在控制台输入的文本 并用"\r\n"结尾
//                 * 之所以用\r\n结尾 是因为我们在handler中添加了 DelimiterBasedFrameDecoder 帧解码。
//                 * 这个解码器是一个根据\n符号位分隔符的解码器。所以每条消息的最后必须加上\n否则无法识别和解码
//                 * */
//                channel.writeAndFlush(line + "\r\n");
//            }
        } finally {
            // The connection is closed automatically on shutdown.
//            group.shutdownGracefully();
        }
    }

    public void writeAndFlush(String message){
        channel.writeAndFlush(message + "\r\n");
    }

    public void loop(){
        while(true){
            if(channel.isActive()){
                ClientRunTimeInfo clientRunTimeInfo = new ClientRunTimeInfo();

                int size = connectManager.getClientConnectorMap().size();
                clientRunTimeInfo.setConnectCount(size);

                long vmFree = 0;
                long vmUse = 0;
                long vmTotal = 0;
                long vmMax = 0;
                int byteToMb = 1024 * 1024;
                Runtime rt = Runtime.getRuntime();
                vmTotal = rt.totalMemory() / byteToMb;
                vmFree = rt.freeMemory() / byteToMb;
                vmMax = rt.maxMemory() / byteToMb;
                vmUse = vmTotal - vmFree;
                float percent = (float)vmUse / (float)vmTotal;
                clientRunTimeInfo.setMemoryPercent((int)(percent * 100)+"%");

                String message = JSON.toJSONString(clientRunTimeInfo);
                writeAndFlush(message);
                try {
                    TimeUnit.SECONDS.sleep(3);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
